package com.siyuanren.gcocp.web.wx.handler;

import com.siyuanren.gcocp.entity.WxUser;
import com.siyuanren.gcocp.service.WxUserService;
import com.siyuanren.gcocp.web.wx.service.CoreService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author guwr
 * @date 2018/4/8
 */
@Slf4j
@Component
public class SubscribeHandler implements WxMpMessageHandler {
    @Autowired
    protected CoreService coreService;
    @Autowired
    protected WxUserService userService;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
        log.info("SubscribeHandler");
        WxMpUser wxMpUser = coreService.getUserInfo(wxMessage.getFromUser(), "zh_CN");
        if (wxMpUser == null) {
            log.info("SubscribeHandler wxMpUser is null");
            return null;
        }
        String openId = wxMpUser.getOpenId();
        WxUser entity = userService.getByOpenid(openId);
        if (entity == null) {
            //库中不存在
            userService.insertWxMpUser(wxMpUser);
        } else {
            userService.update(entity,wxMpUser);
        }
        WxMpXmlOutTextMessage m = WxMpXmlOutMessage.TEXT()
                .content("尊敬的" + wxMpUser.getNickname() + "，您好！")
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
        return m;
    }
}
